import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { useAuthStore } from './store';
import { globalMessage } from '../utils/message';
import type { 
  Product, 
  Case, 
  Settings, 
  User, 
  LoginRequest,
  LoginResponse,
  ProductProcess,
  ProductSpecification,
  ProcessSpecification
} from '../types';

// 导入统一的API类型定义
import {
  ApiResponse,
  PaginatedResponse,
  ErrorResponse,
  UploadResponse,
  PaginationParams,
  ProductQueryParams,
  CaseQueryParams,
  TagQueryParams,
  BannerQueryParams,
  CreateProductRequest,
  UpdateProductRequest,
  CreateCaseRequest,
  UpdateCaseRequest,
  CreateTagRequest,
  UpdateTagRequest,
  CreateBannerRequest,
  UpdateBannerRequest
} from '../types/api';

// API 基础配置
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001/api';

// 扩展 AxiosRequestConfig 以支持自定义元数据
interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  metadata?: {
    startTime?: Date;
  };
}

// 扩展 axios 模块以支持自定义属性
declare module 'axios' {
  interface InternalAxiosRequestConfig {
    metadata?: {
      startTime?: Date;
    };
  }
}

// 创建 axios 实例
const apiClient: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000, // 增加超时时间到30秒
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const url = config.url || '';
    const method = config.method?.toLowerCase() || 'get';
    
    // 定义不需要认证的公开接口
    const publicEndpoints = [
      '/products',
      '/cases',
      '/settings/public',

    ];
    
    // 检查是否为公开接口的GET请求
    const isPublicGetRequest = method === 'get' && publicEndpoints.some(endpoint => url.includes(endpoint));
    
    // 只对需要认证的接口添加token
    if (!isPublicGetRequest) {
      const token = localStorage.getItem('auth_token') || useAuthStore.getState().token;
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
    }
    
    // 添加请求时间戳
    config.metadata = { startTime: new Date() };
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response: AxiosResponse) => {
    // 计算请求耗时
    const endTime = new Date();
    const config = response.config as CustomAxiosRequestConfig;
    // console.log(`API请求耗时: ${endTime.getTime() - (config.metadata?.startTime?.getTime() || 0)}ms - ${response.config.url}`);
    
    // 只对特定的写操作显示成功提示，避免对GET请求显示提示
    const method = config.method?.toLowerCase() || 'get';
    const url = config.url || '';
    
    // 根据响应数据中的message显示提示，如果没有则使用默认提示
    const responseMessage = response.data?.message;
    
    // 不需要显示成功提示的接口列表（通常是查询类接口）
    const silentSuccessUrls = [
      '/dashboard/stats',
      '/dashboard/monthly', 
      '/dashboard/system-status',
      '/logs',
      '/settings/product-categories',
      '/settings/case-categories',
      '/products',
      '/cases',
      '/users'
    ];
    
    // 检查是否为GET请求或不需要提示的接口
    const shouldShowSuccess = method !== 'get' && !silentSuccessUrls.some(silentUrl => url.includes(silentUrl));
    
    // 只对特定操作显示成功提示
    if (shouldShowSuccess) {
      if (url.includes('/login')) {
        globalMessage.success(responseMessage || '登录成功');
      } else if (url.includes('/logout')) {
        globalMessage.success(responseMessage || '退出成功');
      } else if (method === 'post') {
        if (url.includes('/users')) {
          globalMessage.success(responseMessage || '用户创建成功');
        } else if (url.includes('/products')) {
          globalMessage.success(responseMessage || '产品创建成功');
        } else if (url.includes('/cases')) {
          globalMessage.success(responseMessage || '案例创建成功');

        } else if (url.includes('/backup')) {
          globalMessage.success(responseMessage || '备份创建成功');
        } else if (url.includes('/upload')) {
          globalMessage.success(responseMessage || '上传成功');
        }
      } else if (method === 'put' || method === 'patch') {
        if (url.includes('/users')) {
          globalMessage.success(responseMessage || '用户更新成功');
        } else if (url.includes('/products')) {
          globalMessage.success(responseMessage || '产品更新成功');
        } else if (url.includes('/cases')) {
          globalMessage.success(responseMessage || '案例更新成功');
        } else if (url.includes('/settings')) {
          globalMessage.success(responseMessage || '设置更新成功');
        } else if (url.includes('/toggle-status')) {
          globalMessage.success(responseMessage || '状态更新成功');
        } else if (url.includes('/sort')) {
          globalMessage.success(responseMessage || '排序更新成功');
        }
      } else if (method === 'delete') {
        if (url.includes('/users')) {
          globalMessage.success(responseMessage || '用户删除成功');
        } else if (url.includes('/products')) {
          globalMessage.success(responseMessage || '产品删除成功');
        } else if (url.includes('/cases')) {
          globalMessage.success(responseMessage || '案例删除成功');

        } else if (url.includes('/logs')) {
          globalMessage.success(responseMessage || '日志清空成功');
        }
      }
    }
    
    return response;
  },
  (error) => {
    // 处理超时错误
    if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
      globalMessage.error('请求超时，请重试');
      return Promise.reject(new Error('请求超时'));
    }
    
    // 处理网络错误
    if (!error.response) {
      globalMessage.error('网络连接失败，请检查网络');
      // console.error('网络错误:', error.message);
      return Promise.reject(new Error('网络连接失败'));
    }
    
    // 获取错误信息
    const errorMessage = error.response?.data?.message || '服务器内部错误';
    const status = error.response?.status;
    const url = error.config?.url || '';
    
    // 记录详细错误信息
    // console.error(`API错误 [${status}] ${url}:`, {
    //   message: errorMessage,
    //   status,
    //   data: error.response?.data,
    //   config: error.config
    // });
    
    // 处理不同类型的错误
    switch (status) {
      case 400:
        globalMessage.error(errorMessage || '请求参数错误');
        break;
      case 401:
        globalMessage.error('登录已过期，请重新登录');
        const authStore = useAuthStore.getState();
        authStore.logout();
        // 延迟跳转，确保message显示
        setTimeout(() => {
          window.location.href = '/login';
        }, 1000);
        return Promise.reject(new Error('认证失败'));
      case 403:
        globalMessage.error('权限不足，无法访问');
        break;
      case 404:
        globalMessage.error('请求的资源不存在');
        break;
      case 409:
        globalMessage.error(errorMessage || '数据冲突');
        break;
      case 422:
        globalMessage.error(errorMessage || '数据验证失败');
        break;
      case 429:
        globalMessage.error('请求过于频繁，请稍后重试');
        break;
      case 500:
        globalMessage.error('服务器内部错误');
        break;
      case 502:
        globalMessage.error('网关错误');
        break;
      case 503:
        globalMessage.error('服务暂时不可用');
        break;
      default:
        globalMessage.error('请求失败，请重试');
    }
    
    return Promise.reject(new Error(errorMessage));
  }
);



// 认证API
export const authApi = {
  // 登录
  login: async (data: LoginRequest): Promise<LoginResponse> => {
    const response = await apiClient.post<ApiResponse<LoginResponse>>('/auth/login', data);
    return response.data.data;
  },
  
  // 退出登录
  logout: async (): Promise<void> => {
    await apiClient.post('/auth/logout');
  },
  
  // 获取当前用户信息
  getCurrentUser: async (): Promise<User> => {
    const response = await apiClient.get<ApiResponse<User>>('/auth/me');
    return response.data.data;
  },
  
  // 获取用户资料 (getProfile别名)
  getProfile: async (): Promise<User> => {
    const response = await apiClient.get<ApiResponse<User>>('/auth/me');
    return response.data.data;
  },
  
  // 刷新token
  refreshToken: async (): Promise<{ token: string }> => {
    const response = await apiClient.post<ApiResponse<{ token: string }>>('/auth/refresh');
    return response.data.data;
  }
};

// 产品API
export const productApi = {
  // 获取产品列表
  getProducts: async (params?: {
    page?: number;
    limit?: number;
    search?: string;
    type?: string; // 产品类型
    status?: string;
    featured?: boolean;
    material?: string;
    priceRange?: string;
    priceMin?: number; // 最低价格筛选
    priceMax?: number; // 最高价格筛选
    unit?: string; // 单位筛选
  }): Promise<{ products: Product[]; total: number }> => {
    // console.log('🌐 API - 发送产品请求:', params);
    const response = await apiClient.get<any>('/products', { params });
    // console.log('📡 API - 原始响应:', response);
    // console.log('📋 API - 响应数据:', response.data);
    // console.log('🎯 API - 最终数据:', response.data.data);
    // console.log('🔍 API - 分页信息:', response.data.pagination);
    return {
      products: response.data.data || [],
      total: response.data.pagination?.total || 0
    };
  },
  
  // 获取产品详情
  getProduct: async (id: string): Promise<Product> => {
    const response = await apiClient.get<ApiResponse<Product>>(`/products/${id}`);
    return response.data.data;
  },
  
  // 创建产品
  createProduct: async (data: Omit<Product, 'id' | 'createdAt' | 'updatedAt'>): Promise<Product> => {
    const response = await apiClient.post<ApiResponse<Product>>('/products', data);
    return response.data.data;
  },
  
  // 更新产品
  updateProduct: async (id: string, data: Partial<Product>): Promise<Product> => {
    const response = await apiClient.put<ApiResponse<Product>>(`/products/${id}`, data);
    return response.data.data;
  },
  
  // 删除产品
  deleteProduct: async (id: string): Promise<void> => {
    await apiClient.delete(`/products/${id}`);
  },
  
  // 注意：产品分类功能已移除，后端不再支持分类表

  // 获取产品工艺列表
  getProductProcesses: async (productId: string): Promise<ProductProcess[]> => {
    const response = await apiClient.get<ApiResponse<ProductProcess[]>>(`/products/${productId}/processes`);
    return response.data.data;
  },

  // 获取单个产品工艺
  getProductProcess: async (productId: string, processId: string): Promise<ProductProcess> => {
    const response = await apiClient.get<ApiResponse<ProductProcess>>(`/products/${productId}/processes/${processId}`);
    return response.data.data;
  },

  // 创建产品工艺
  createProductProcess: async (productId: string, data: Omit<ProductProcess, 'id' | 'productId' | 'createdAt' | 'updatedAt'>): Promise<ProductProcess> => {
    const response = await apiClient.post<ApiResponse<ProductProcess>>(`/products/${productId}/processes`, data);
    return response.data.data;
  },

  // 更新产品工艺
  updateProductProcess: async (productId: string, processId: string, data: Partial<ProductProcess>): Promise<ProductProcess> => {
    const response = await apiClient.put<ApiResponse<ProductProcess>>(`/products/${productId}/processes/${processId}`, data);
    return response.data.data;
  },

  // 删除产品工艺
  deleteProductProcess: async (productId: string, processId: string): Promise<void> => {
    await apiClient.delete(`/products/${productId}/processes/${processId}`);
  },

  // 获取产品参数列表
  getProductSpecifications: async (productId: string): Promise<ProductSpecification[]> => {
    const response = await apiClient.get<ApiResponse<ProductSpecification[]>>(`/products/${productId}/specifications`);
    return response.data.data;
  },

  // 创建产品参数
  createProductSpecification: async (productId: string, data: Omit<ProductSpecification, 'id' | 'productId' | 'createdAt' | 'updatedAt'>): Promise<ProductSpecification> => {
    const response = await apiClient.post<ApiResponse<ProductSpecification>>(`/products/${productId}/specifications`, data);
    return response.data.data;
  },

  // 批量创建产品参数
  createProductSpecifications: async (productId: string, data: Omit<ProductSpecification, 'id' | 'productId' | 'createdAt' | 'updatedAt'>[]): Promise<ProductSpecification[]> => {
    const response = await apiClient.post<ApiResponse<ProductSpecification[]>>(`/products/${productId}/specifications/batch`, { specifications: data });
    return response.data.data;
  },

  // 更新产品参数
  updateProductSpecification: async (productId: string, specId: string, data: Partial<ProductSpecification>): Promise<ProductSpecification> => {
    const response = await apiClient.put<ApiResponse<ProductSpecification>>(`/products/${productId}/specifications/${specId}`, data);
    return response.data.data;
  },

  // 删除产品参数
  deleteProductSpecification: async (productId: string, specId: string): Promise<void> => {
    await apiClient.delete(`/products/${productId}/specifications/${specId}`);
  },

  // 批量删除产品参数
  deleteProductSpecifications: async (productId: string, specIds: string[]): Promise<void> => {
    await apiClient.delete(`/products/${productId}/specifications/batch`, { data: { specIds } });
  },

  // 获取参数分类列表
  getSpecificationCategories: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/products/specifications/categories');
    return response.data.data;
  },

  // 获取产品类型列表
  getProductTypes: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/products/types');
    return response.data.data;
  },

  // 获取材料列表
  getMaterials: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/products/materials');
    return response.data.data;
  },

  // 获取单位列表
  getUnits: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/products/units');
    return response.data.data;
  }
};

// 案例API
export const caseApi = {
  // 获取案例列表
  getCases: async (params?: PaginationParams & {
    category?: string; // 兼容字段
    industry?: string; // 行业分类
    featured?: boolean;
    services?: string; // 服务项目筛选
    tags?: string; // 标签筛选
    clientName?: string; // 客户名称筛选
    duration?: string; // 项目周期筛选
    location?: string; // 项目地点筛选
  }): Promise<{ cases: Case[]; total: number }> => {
    const response = await apiClient.get<any>('/cases', { params });
    console.log('getCases API response:', response.data);
    // 后端返回的格式：{ success: true, data: Case[], pagination: { total: number } }
    return {
      cases: response.data.data || [],
      total: response.data.pagination?.total || 0
    };
  },
  
  // 获取案例详情
  getCase: async (id: string): Promise<Case> => {
    const response = await apiClient.get<ApiResponse<Case>>(`/cases/${id}`);
    return response.data.data;
  },
  
  // 创建案例
  createCase: async (data: Omit<Case, 'id' | 'createdAt' | 'updatedAt'>): Promise<Case> => {
    const response = await apiClient.post<ApiResponse<Case>>('/cases', data);
    return response.data.data;
  },
  
  // 更新案例
  updateCase: async (id: string, data: Partial<Case>): Promise<Case> => {
    const response = await apiClient.put<ApiResponse<Case>>(`/cases/${id}`, data);
    return response.data.data;
  },
  
  // 删除案例
  deleteCase: async (id: string): Promise<void> => {
    await apiClient.delete(`/cases/${id}`);
  },
  
  // 注意：案例行业分类和应用场景功能已移除，后端不再支持相关表
  
  // 获取案例标签
  getTags: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/cases/tags');
    return response.data.data;
  },

  // 获取应用场景标签
  getApplicationScenes: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/cases/application-scenes');
    return response.data.data;
  },

  // 获取热门应用场景
  getPopularApplicationScenes: async (limit?: number): Promise<Array<{ scene: string; count: number }>> => {
    const response = await apiClient.get<ApiResponse<Array<{ scene: string; count: number }>>>('/cases/application-scenes/popular', { params: { limit } });
    return response.data.data;
  },

  // 根据应用场景搜索案例
  getCasesByApplicationScene: async (scene: string, params?: PaginationParams): Promise<{ cases: Case[]; total: number }> => {
    const response = await apiClient.get<ApiResponse<{ cases: Case[]; total: number }>>(`/cases/application-scenes/${encodeURIComponent(scene)}`, { params });
    return response.data.data;
  },

  // 获取应用场景统计
  getApplicationSceneStats: async (): Promise<Array<{ scene: string; count: number }>> => {
    const response = await apiClient.get<ApiResponse<Array<{ scene: string; count: number }>>>('/cases/application-scenes/stats');
    return response.data.data;
  },

  // 获取案例行业列表
  getCaseIndustries: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/cases/industries');
    return response.data.data;
  },

  // 获取服务项目列表
  getServices: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/cases/services');
    return response.data.data;
  },

  // 获取项目亮点列表
  getHighlights: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/cases/highlights');
    return response.data.data;
  },

  // 获取客户名称列表
  getClientNames: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/cases/clients');
    return response.data.data;
  },

  // 获取项目地点列表
  getLocations: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/cases/locations');
    return response.data.data;
  }
};



// 设置API
export const settingsApi = {
  // 获取设置（需要认证）
  getSettings: async (): Promise<Settings> => {
    const response = await apiClient.get<ApiResponse<Settings>>('/settings');
    return response.data.data;
  },
  
  // 获取公开设置（无需认证）
  getPublicSettings: async (): Promise<any> => {
    const response = await apiClient.get<ApiResponse<any>>('/settings/public');
    return response.data.data;
  },
  
  // 更新设置
  updateSettings: async (data: Partial<Settings>): Promise<Settings> => {
    const response = await apiClient.put<ApiResponse<Settings>>('/settings', data);
    return response.data.data;
  },
  
  // 更新单个设置项
  updateSetting: async (key: string, value: any): Promise<any> => {
    const response = await apiClient.put<ApiResponse<any>>(`/settings/${key}`, { value });
    return response.data.data;
  },
  
  // 获取产品分类
  getProductCategories: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/settings/product-categories');
    return response.data.data;
  },
  
  // 更新产品分类
  updateProductCategories: async (categories: string[]): Promise<void> => {
    await apiClient.put('/settings/product-categories', { categories });
  },
  
  // 获取产品标签
  getProductTags: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/settings/product-tags');
    return response.data.data;
  },
  
  // 更新产品标签
  updateProductTags: async (tags: string[]): Promise<void> => {
    await apiClient.put('/settings/product-tags', { tags });
  },
  
  // 获取案例分类
  getCaseCategories: async (): Promise<string[]> => {
    const response = await apiClient.get<ApiResponse<string[]>>('/settings/case-categories');
    return response.data.data;
  },
  
  // 更新案例分类
  updateCaseCategories: async (categories: string[]): Promise<void> => {
    await apiClient.put('/settings/case-categories', { categories });
  },

  // 删除产品分类
  deleteProductCategory: async (category: string): Promise<void> => {
    await apiClient.delete(`/settings/product-categories/${encodeURIComponent(category)}`);
  },

  // 创建产品分类
  createProductCategory: async (data: { name: string; description?: string }): Promise<{ id: string }> => {
    const response = await apiClient.post<ApiResponse<{ id: string }>>('/settings/product-categories', data);
    return response.data.data;
  },

  // 更新产品分类
  updateProductCategory: async (id: string, data: { name: string; description?: string }): Promise<void> => {
    await apiClient.put(`/settings/product-categories/${id}`, data);
  },

  // 删除案例分类
  deleteCaseCategory: async (id: string): Promise<void> => {
    await apiClient.delete(`/settings/case-categories/${id}`);
  },

  // 创建案例分类
  createCaseCategory: async (data: { name: string; description?: string }): Promise<{ id: string }> => {
    const response = await apiClient.post<ApiResponse<{ id: string }>>('/settings/case-categories', data);
    return response.data.data;
  },

  // 更新案例分类
  updateCaseCategory: async (id: string, data: { name: string; description?: string }): Promise<void> => {
    await apiClient.put(`/settings/case-categories/${id}`, data);
  }
};

// 文件上传API
export const uploadApi = {
  // 上传文件
  uploadFile: async (file: File, type: 'image' | 'document' = 'image'): Promise<{ url: string; filename: string }> => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', type);
    
    const response = await apiClient.post<ApiResponse<{ url: string; filename: string }>>('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    return response.data.data;
  },
  
  // 删除文件
  deleteFile: async (filename: string): Promise<void> => {
    await apiClient.delete(`/upload/${filename}`);
  }
};



// 联系人管理 API
export const contactApi = {
  // 获取所有联系人（管理端）
  getContacts: async (): Promise<Array<{
    id: string;
    type: 'primary' | 'secondary';
    name: string;
    title?: string;
    phone: string;
    wechat?: string;
    email?: string;
    description?: string;
    status: 'active' | 'inactive';
    sort: number;
    createdAt: string;
    updatedAt: string;
  }>> => {
    const response = await apiClient.get<ApiResponse<Array<{
      id: string;
      type: 'primary' | 'secondary';
      name: string;
      title?: string;
      phone: string;
      wechat?: string;
      email?: string;
      description?: string;
      status: 'active' | 'inactive';
      sort: number;
      createdAt: string;
      updatedAt: string;
    }>>>('/contacts');
    return response.data.data;
  },

  // 获取公开联系人信息（前端使用）
  getPublicContacts: async (): Promise<Array<{
    id: string;
    type: 'primary' | 'secondary';
    name: string;
    title?: string;
    position?: string;
    phone: string;
    wechat?: string;
    wechatQr?: string;
    email?: string;
    description?: string;
  }>> => {
    const response = await apiClient.get<ApiResponse<Array<{
      id: string;
      type: 'primary' | 'secondary';
      name: string;
      title?: string;
      position?: string;
      phone: string;
      wechat?: string;
      wechatQr?: string;
      email?: string;
      description?: string;
    }>>>('/contacts/public');
    return response.data.data;
  },

  // 获取单个联系人
  getContact: async (id: string): Promise<{
    id: string;
    type: 'primary' | 'secondary';
    name: string;
    title?: string;
    position?: string;
    phone: string;
    wechat?: string;
    wechatQr?: string;
    email?: string;
    description?: string;
    status: 'active' | 'inactive';
    sort: number;
    createdAt: string;
    updatedAt: string;
  }> => {
    const response = await apiClient.get<ApiResponse<{
      id: string;
      type: 'primary' | 'secondary';
      name: string;
      title?: string;
      position?: string;
      phone: string;
      wechat?: string;
      wechatQr?: string;
      email?: string;
      description?: string;
      status: 'active' | 'inactive';
      sort: number;
      createdAt: string;
      updatedAt: string;
    }>>(`/contacts/${id}`);
    return response.data.data;
  },

  // 创建联系人
  createContact: async (data: {
    type: 'primary' | 'secondary';
    name: string;
    title?: string;
    position?: string;
    phone: string;
    wechat?: string;
    wechatQr?: string;
    email?: string;
    description?: string;
    status?: 'active' | 'inactive';
    sort?: number;
  }): Promise<{ id: string }> => {
    const response = await apiClient.post<ApiResponse<{ id: string }>>('/contacts', data);
    return response.data.data;
  },

  // 更新联系人
  updateContact: async (id: string, data: Partial<{
    type: 'primary' | 'secondary';
    name: string;
    title?: string;
    position?: string;
    phone: string;
    wechat?: string;
    wechatQr?: string;
    email?: string;
    description?: string;
    status: 'active' | 'inactive';
    sort: number;
  }>): Promise<void> => {
    await apiClient.put(`/contacts/${id}`, data);
  },

  // 删除联系人
  deleteContact: async (id: string): Promise<void> => {
    await apiClient.delete(`/contacts/${id}`);
  },

  // 批量更新联系人排序
  updateContactsSort: async (contacts: Array<{ id: string; sort: number }>): Promise<void> => {
    await apiClient.put('/contacts/batch/sort', { contacts });
  },

  // 创建联系表单提交
  create: async (data: {
    name: string;
    phone: string;
    email?: string;
    subject: string;
    message: string;
    productName?: string;
    selectedCraftType?: string;
  }): Promise<{ id: string }> => {
    const response = await apiClient.post<ApiResponse<{ id: string }>>('/contact-forms', data);
    return response.data.data;
  }
};

// 用户管理 API
export const userApi = {
  // 获取用户列表
  getUsers: async (params?: PaginationParams): Promise<{ users: User[]; total: number }> => {
    const response = await apiClient.get<ApiResponse<{ users: User[]; total: number; pagination: any }>>('/users', { params });
    return response.data.data;
  },

  // 获取单个用户
  getUser: async (id: string): Promise<User> => {
    const response = await apiClient.get<ApiResponse<User>>(`/users/${id}`);
    return response.data.data;
  },

  // 创建用户
  createUser: async (data: Omit<User, 'id' | 'createdAt' | 'updatedAt'>): Promise<User> => {
    const response = await apiClient.post<ApiResponse<User>>('/users', data);
    return response.data.data;
  },

  // 更新用户
  updateUser: async (id: string, data: Partial<User>): Promise<User> => {
    const response = await apiClient.put<ApiResponse<User>>(`/users/${id}`, data);
    return response.data.data;
  },

  // 删除用户
  deleteUser: async (id: string): Promise<void> => {
    await apiClient.delete(`/users/${id}`);
  },

  // 切换用户状态
  toggleUserStatus: async (id: string): Promise<User> => {
    const response = await apiClient.patch<ApiResponse<User>>(`/users/${id}/toggle-status`);
    return response.data.data;
  }
};

// 统计API
export const statsApi = {
  // 获取仪表板统计
  getDashboardStats: async (): Promise<{
    totalProducts: number;
    totalCases: number;
    totalUploads: number;
  }> => {
    const response = await apiClient.get<ApiResponse<{
      totalProducts: number;
      totalCases: number;
      totalUploads: number;
    }>>('/dashboard/stats');
    return response.data.data;
  },
  
  // 获取月度统计
  getMonthlyStats: async (): Promise<{
    month: string;
    products: number;
    cases: number;
    views: number;
  }[]> => {
    const response = await apiClient.get<ApiResponse<{
      month: string;
      products: number;
      cases: number;
      views: number;
    }[]>>('/dashboard/monthly');
    return response.data.data;
  }
};

// 系统日志API
export const getLogs = async (params?: {
  page?: number;
  limit?: number;
  level?: string;
  startDate?: string;
  endDate?: string;
}): Promise<{
  logs: Array<{
    id: string;
    level: string;
    message: string;
    timestamp: string;
    metadata?: any;
  }>;
  total: number;
  page: number;
  limit: number;
}> => {
  const response = await apiClient.get<ApiResponse<{
    logs: Array<{
      id: string;
      level: string;
      message: string;
      timestamp: string;
      metadata?: any;
    }>;
    total: number;
    page: number;
    limit: number;
  }>>('/logs', { params });
  return response.data.data;
};

// 获取日志统计
export const getLogStats = async (): Promise<{
  total: number;
  error: number;
  warn: number;
  info: number;
}> => {
  const response = await apiClient.get<ApiResponse<{
    total: number;
    error: number;
    warn: number;
    info: number;
  }>>('/logs/stats');
  return response.data.data;
};

// 清理日志
export const cleanupLogs = async (days: number): Promise<{ deleted: number }> => {
  const response = await apiClient.delete<ApiResponse<{ deleted: number }>>(`/logs/cleanup/${days}`);
  return response.data.data;
};

// 导出日志
export const exportLogs = async (params?: {
  startDate?: string;
  endDate?: string;
  level?: string;
}): Promise<Blob> => {
  const response = await apiClient.get('/logs/export', {
    params,
    responseType: 'blob'
  });
  return response.data;
};

// 备份API
export const getBackups = async (): Promise<Array<{
  id: string;
  name: string;
  fileSize: number;
  createdAt: string;
  type: string;
  status: string;
}>> => {
  const response = await apiClient.get<ApiResponse<Array<{
    id: string;
    name: string;
    fileSize: number;
    createdAt: string;
    type: string;
    status: string;
  }>>>('/backup');
  return response.data.data;
};

// 创建备份
export const createBackup = async (data: {
  name: string;
  description?: string;
  tables?: string[];
} = { name: `备份_${new Date().toISOString().split('T')[0]}` }): Promise<{
  id: string;
  name: string;
  fileSize: number;
  createdAt: string;
  type: string;
  status: string;
}> => {
  const response = await apiClient.post<ApiResponse<{
    id: string;
    name: string;
    fileSize: number;
    createdAt: string;
    type: string;
    status: string;
  }>>('/backup', data);
  return response.data.data;
};

// 下载备份
export const downloadBackup = async (id: string): Promise<Blob> => {
  const response = await apiClient.get(`/backup/${id}/download`, {
    responseType: 'blob'
  });
  return response.data;
};

// 删除备份
export const deleteBackup = async (id: string): Promise<void> => {
  await apiClient.delete(`/backup/${id}`);
};

// 恢复备份
export const restoreBackup = async (id: string): Promise<{ success: boolean; message: string }> => {
  const response = await apiClient.post<ApiResponse<{ success: boolean; message: string }>>(`/backup/${id}/restore`);
  return response.data.data;
};

// 导出默认的 apiClient
export default apiClient;